<?php

namespace App\Http\Middleware;

use App\Models\XcUserXiche;
use Closure;
use Illuminate\Http\Response;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class ApiAuthCheck
{
    /**
     * handle 验证api_token合法性
     * @param $request
     * @param Closure $next
     * @param string $action
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|mixed
     */
    public function handle($request, Closure $next, $action = '')
    {
        $api = $request->get("api_token");
        $token = json_decode(Redis::get($api), true);
        if (empty($token)){
            $user = XcUserXiche::where('api_token', $api)->first();
            if (empty($user)){
                return response()->json(['code' => -1, 'msg' => '无效token']);
            }
            // $user->roles = $user->roles()->get()->toArray();

            Redis::setex($user->api_token , 1800 , json_encode($user));//30分钟有效期
        }
        return $next($request);
    }
}
